
import shlex
import subprocess
import platform

def run_command(command):
    print(1)
    try:
        # 根据操作系统设置编码
        encoding = 'gbk' if platform.system() == 'Windows' else 'utf-8'
        print(1)
        # 构造命令
        if platform.system() == 'Windows':
            # safe_command = shlex.quote(command)
            cmd = [command]
        else:
            cmd = ['/bin/bash', '-c', command]
        print(cmd)
        result = subprocess.run(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            encoding=encoding,  # 动态选择编码
            errors='replace'    # 替换无法解码的字符
        )
        print(1)
        # 清理输出
        stdout = result.stdout.strip()
        stderr = result.stderr.strip()
        
        if result.returncode == 0:
            print(f"stdout type: {type(result.stdout)}, content: {repr(result.stdout)}")
            return f'执行成功\n{stdout}'
        else:
            print(f"stderr type: {type(result.stderr)}, content: {repr(result.stderr)}")
            return f'执行失败\n{stderr}'
    except Exception as e:
        return f'执行异常\n{str(e)}'


# cmdtest = r'C:\Python27\python.exe C:\Users\Administrator\Desktop\robot_20250509\robot\baxin_robot\count.py'
# run_command(cmdtest)


